package com.xindacloud.sms.adapter.service.factory;

import com.nexmo.client.HttpConfig;
import com.nexmo.client.NexmoClient;
import com.xindacloud.sms.adapter.entity.SmsAgent;
import com.xindacloud.sms.adapter.entity.SmsAgentGroup;
import com.xindacloud.sms.adapter.exception.ServiceException;
import com.xindacloud.sms.adapter.service.business.ISmsAgentGroupService;
import com.xindacloud.sms.adapter.service.business.ISmsAgentService;
import com.xindacloud.sms.adapter.utils.AgentEnum;
import com.xindacloud.sms.adapter.utils.Base64DecodeHelp;
import com.xindacloud.sms.adapter.utils.UnionResultHelp;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
//@Scope("prototype")
public class NexmoClientFactory {

    private static final String NEXMO_DEFAULT_AGENT = "nexmoDefaultAgent";
    private final ISmsAgentService smsAgentService;

    private final ISmsAgentGroupService smsAgentGroupService;

    private static Map<String, SmsAgent> nexmoDefaultAgentMap = new HashMap<>();

    @Autowired
    public NexmoClientFactory(ISmsAgentService smsAgentService, ISmsAgentGroupService smsAgentGroupService) {
        this.smsAgentService = smsAgentService;
        this.smsAgentGroupService = smsAgentGroupService;
    }


    public NexmoClient getNexmoClient(String apiKey, String apiSecret, String baseUri) {
        NexmoClient.Builder builder = NexmoClient.builder()
                .apiKey(apiKey)
                .apiSecret(apiSecret);
        if (baseUri.startsWith(HttpConfig.defaultConfig().getApiBaseUri())) {
            builder.httpConfig(HttpConfig.builder().apiBaseUri(baseUri).build());
        }
        if (baseUri.startsWith(HttpConfig.defaultConfig().getRestBaseUri())) {
            builder.httpConfig(HttpConfig.builder().restBaseUri(baseUri).build());
        }
        if (baseUri.startsWith(HttpConfig.defaultConfig().getSnsBaseUri())) {
            builder.httpConfig(HttpConfig.builder().snsBaseUri(baseUri).build());
        }
        return builder.build();
    }


    public NexmoClient getRandomNexmoClient() throws ServiceException {

        if (Objects.isNull(nexmoDefaultAgentMap.get(NEXMO_DEFAULT_AGENT))) {
            SmsAgentGroup smsAgentGroup = smsAgentGroupService.queryOneAgentInfoByName(AgentEnum.NEXMO_AGENT.getAgentName());
            if (Objects.isNull(smsAgentGroup)) {
                throw new ServiceException("没有找到通道,请在代理商组中添加.", UnionResultHelp.StatusEnum.NotFound.code());
            }

            final List<SmsAgent> smsAgents = Optional.ofNullable(smsAgentService.queryAvailableAgent(smsAgentGroup.getGroupId()))
                    .orElseThrow(() -> new ServiceException("没有可用的服务通道.", UnionResultHelp.StatusEnum.NotFound.code()));

            SmsAgent nexmoDefaultAgent = smsAgents.stream()
                    .filter(smsAgent -> BooleanUtils.isTrue(smsAgent.getIsDefault()))
                    .findAny()
                    .orElse(smsAgents.get(new Random().nextInt(smsAgents.size())));
            nexmoDefaultAgentMap.put(NEXMO_DEFAULT_AGENT, nexmoDefaultAgent);
        }
        final SmsAgent defaultAgent = nexmoDefaultAgentMap.get(NEXMO_DEFAULT_AGENT);
        if (Objects.isNull(defaultAgent)) {
            throw new ServiceException("无可用的通道.", UnionResultHelp.StatusEnum.NotFound.code());
        }
        return getNexmoClient(Base64DecodeHelp.decode(defaultAgent.getApiKey()), Base64DecodeHelp.decode(defaultAgent.getApiSecret()), defaultAgent.getApiUrl());

    }
}
